﻿using System.Collections.Generic;

namespace XCI.Core
{
    /// <summary>
    /// 数据字典
    /// </summary>
    public class Dic
    {
        private readonly string _code;
        private readonly List<DicItem> _items;

        /// <summary>
        /// 初始化数据字典
        /// </summary>
        /// <param name="code">字典编码</param>
        /// <param name="items">字典项集合</param>
        public Dic(string code, List<DicItem> items)
        {
            _code = code;
            _items = items ?? new List<DicItem>();
        }

        /// <summary>
        /// 获取字典类型编码
        /// </summary>
        public string Code => _code;

        /// <summary>
        /// 获取字典列表
        /// </summary>
        public List<DicItem> Items => _items;
         
        /// <summary>
        /// 根据值获取名称
        /// </summary>
        /// <param name="value">字典值</param>
        /// <param name="defaultName">如果找不到则返回此值</param>
        public string GetNameByValue(object value, string defaultName)
        {
            if (value == null || string.IsNullOrEmpty(value.ToString())) return defaultName;
            foreach (var item in _items)
            {
                if (item.Value.Equals(value.ToString()))
                {
                    return item.Name;
                }
            }
            return defaultName;
        }

        /// <summary>
        /// 根据名称获取值
        /// </summary>
        /// <param name="name">字典名称</param>
        /// <param name="defaultValue">如果找不到则返回此值</param>
        public string GetValueByName(string name, string defaultValue)
        {
            if (name == null || string.IsNullOrEmpty(name.ToString())) return defaultValue;
            foreach (var item in _items)
            {
                if (item.Name.Equals(name))
                {
                    return item.Value;
                }
            }
            return defaultValue;
        }
    }

    /// <summary>
    /// 字典项
    /// </summary>
    public class DicItem
    {
        /// <summary>
        /// 字典主键
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// 上级主键
        /// </summary>
        public string ParentId { get; set; }

        /// <summary>
        /// 字典类型编码
        /// </summary>
        public string Code { get; set; }

        /// <summary>
        /// 字典名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 名称简拼
        /// </summary>
        public string Spell { get; set; }

        /// <summary>
        /// 字典值
        /// </summary>
        public string Value { get; set; }

        /// <summary>
        /// 序号
        /// </summary>
        public int Path { get; set; }
    }
}
